package name.vaccari.matteo.tai.lezione03;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class TrisServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		List<String> cells = new TrisController().execute(req.getPathInfo(), 
				req.getParameter("nextPlayer"));
		
		Map<String, Object> model = new HashMap<String, Object>(); 
		model.put("cell", cells);
		PrintWriter writer = resp.getWriter();
		processTemplate("tris.ftl", model, writer);
		writer.flush();
	}

	private void processTemplate(String name, Map<String, Object> model, Writer writer) {
		Template template = getTemplate(name);
		try {
			template.process(model, writer);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	private Template getTemplate(String name) {
		try {
			Configuration configuration = new Configuration();
			configuration.setDirectoryForTemplateLoading(new File("./views"));
			return configuration.getTemplate(name);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	
}
